﻿// 总数据

var articleData = {

    isSearching: false,
    info: "",
    start_date: "",
    end_date: "",
    success: [],
    failed: [],
    requestData:{}

};


var orderData = [];

// 翻页

var page = 0;

var collection_logs = [];

var isRuning = false;

var autorefresh = setInterval(autoRefreshSeller, 60 * 3 * 60 * 1000);

var isAmazonLogin = 0;




// 匹配到的订单数

var currentDate = null;


// 是否已经安装了插件

var isInstall = false;


var isRun = false;

var log_lis = getLogLisCache();


var base_uri = 'https://www.haimaihome.com';
// var base_uri = 'http://www.haimaihome.local';

var baseUri = '/gp/site-metrics/load-report-JSON.html';

var amazonSessionUrl = '';

var requestTotalNum = 0;

var isRequestRun = true;

var loginProfile;

var currentSeller;

var failedLog = [];



var selectedUrl = ''

var scrollTop = 0




var messageObj = {

    finsh: true

}



var isGetEmailing = false


var customerProfile = getProfileCache();


var isFirst = true

var formData = {};

$(function () {
    autoCheckLogin();
    setInterval(autoCheckLogin, 3000);
});

Array.prototype.indexOf = function(val) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == val) return i;
    }
    return -1;
};
Array.prototype.remove = function(val) {
    var index = this.indexOf(val);
    if (index > -1) {
        this.splice(index, 1);
    }
};

chrome.webRequest.onBeforeRequest.addListener(

    function (details) {
        //正在登录
        if (isAmazonLogin == 0) {
            isAmazonLogin = 1;
        }
    }, {
        urls: [
            "*://sellercentral.amazon.com/*", "*://sellercentral.amazon.co.jp/*", "*://sellercentral.amazon.ca/*",
            "*://sellercentral.amazon.co.uk/*", "*://sellercentral.amazon.de/*", "*://sellercentral.amazon.fr/*",
            "*://sellercentral.amazon.it/*", "*://sellercentral.amazon.es/*", "*://sellercentral.amazon.in/*",
            "*://sellercentral.amazon.com.mx/*"
        ]
    });




chrome.webRequest.onCompleted.addListener(

    function (details) {
    }, {

        urls: ["*://sellercenter.amazon.com/*", "*://sellercenter.amazon.co.jp/*", "*://*.amazon.ca/*", "*://*.amazon.co.uk/*", "*://*.amazon.de/*", "*://*.amazon.fr/*", "*://*.amazon.it/*", "*://*.amazon.es/*", "*://*.amazon.in/*", "*://*.amazon.com.mx/*"]

    }, ["responseHeaders"]);


function autoCheckLogin()
{
    if (customerProfile.sellerId == '') {
        console.log('check login');
        console.log(customerProfile, currentSeller);
        chrome.tabs.query({
            url: [
                "*://sellercentral.amazon.com/*", "*://sellercentral.amazon.co.jp/*", "*://sellercentral.amazon.ca/*",
                "*://sellercentral.amazon.co.uk/*", "*://sellercentral.amazon.de/*", "*://sellercentral.amazon.fr/*",
                "*://sellercentral.amazon.it/*", "*://sellercentral.amazon.es/*", "*://sellercentral.amazon.in/*",
                "*://sellercentral.amazon.com.mx/*"],
            status: 'complete',
            active: true
        }, function (result) {

            console.log(result);
            if (result.length > 0) {
                chrome.tabs.sendMessage(result[0].id, {
                    type: 'parseSellerId',
                }, function (response) {
                })
            }

        });
    }
}

// 监听来自popup.js和content_script.js的消息

function isAmazonLogined()
{
    var customerProfile = chrome.storage.local.get(['customerProfile'], function (items) {
        return items.customerProfile;
    });
    console.log(customerProfile);

    return  customerProfile !== undefined ? true : false;
}



chrome.runtime.onMessage.addListener(function (request, sender, sendRequest) {

    if (request.type === 'getMerProfile') {
        var profile = request.data;
        if (profile.merchantId && profile.marketplaceId) {
            customerProfile.sellerId = profile.merchantId;
            customerProfile.marketplaceId = profile.marketplaceId;
            isAmazonLogin = 2;
            console.log(isAmazonLogin);
            chrome.storage.local.set({customerProfile: customerProfile}, function () {
                console.log('用户信息保存成功');
            });
        }
    } else if (request.type === 'storeLoginProfile') {
        console.log(request.type);
        loginProfile = request.data;
        chrome.storage.local.set({loginProfile: request.data}, function () {
            console.log(request.data);
        });
    } else if (request.type === 'currentSellerCatch') {
        //获取session
        currentSeller = request.data;
        chrome.storage.local.set({currentSeller: currentSeller}, function () {
            console.log('用户marketplaces保存成功');
            beginCatch();
        });
    }
});

function beginCatch() {
    console.log(articleData);
    console.log(currentSeller);
    console.log(customerProfile);
    if (articleData.isSearching === false) {
        articleData.isSearching = true;
        var marketplaces = currentSeller.marketplace;
        if (customerProfile.sellerId === currentSeller.SellerId) {
            for (var i=0; i<marketplaces.length; i++) {
                if (marketplaces[i].is_traffics == 1) {
                    setTimeout(cathSingleSiteSessions(marketplaces[i].marketplaceId, marketplaces[i].unTraffics, marketplaces[i].site, currentSeller.SellerId), 20000);
                }
            }
            chrome.storage.local.set({currentSeller: currentSeller}, function () {
                console.log('用户marketplaces保存成功');
            });
        } else {
            articleData.info = '用户不匹配';
            currentSeller = null;
        }
    }
    articleData.info = '';
    articleData.isSearching = false;

}

function cathSingleSiteSessions(marketplaceId, unTraffics,site, SellerId) {
    console.log('正在收集' + site + '站点下的数据');
    console.log(unTraffics);
    for (var j=0; j<unTraffics.length; j++) {
        articleData.info = '正在收集' + site + '站点下['+unTraffics[j]+']的数据';
        setTimeout(requestAmazonSession(unTraffics[j], site, marketplaceId, SellerId), 5000);
        console.log(articleData);
    }
}

function requestAmazonSession(date, site, marketId, SellerId) {
     recurRequestAmazonData([], site, date, marketId, SellerId,0);
    // if (rows.length != 0) {
    //     post.data = rows;
    //     setTimeout(saveToServer(post), 2000);
    // }

}

function recurRequestAmazonData(rows, site, date,  marketplaceId, SellerId, page)
{
    var amazonSessionUrl = getCatchUrl(site);
    $.ajax({
        url: amazonSessionUrl,
        data: getRequestParam(date, page),
        dataType: 'json',
        method: 'GET',
        // async: false,
        timeout: 10000,
    }).done(function(data){
        if (data.data.rows.length != 0) {
            rows = rows.concat(data.data.rows);
            console.log(rows);
            recurRequestAmazonData(rows, site, date,  marketplaceId, SellerId, page + 1);
        } else {
            if (rows.length != 0) {
                var headers = data.headers.show;
                var post = {
                    date: date,
                    data: [],
                    headers: headers,
                    site: site,
                    marketId: marketplaceId,
                    SellerId: SellerId
                };
                post.data = rows;
                setTimeout(saveToServer(post), 2000);
            }
        }
    }).fail(function () {
        rows  = []
    });
}

function saveToServer(post) {
    $.ajax({
        url : base_uri + '/api/receiveSessions',
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(post),
        method: 'POST',
        success: function (fv) {
            logSuccess(post.date, post.marketId);
        },
        error: function (fv) {
            // putLogCache(start, 0);
        },
        timeout: 10000,
    });
}

//自动更新当前保存的用户信息，并且后台自动更新数据
function autoRefreshSeller() {
    console.log('更新seller');
    console.log(currentSeller);
    if (currentSeller !== undefined && customerProfile.sellerId === currentSeller.SellerId) {
        //自动获取当前marketplace的数据
        $.ajax({
            url: base_uri + '/api/getMarketplaces/' + customerProfile.sellerId,
            dataType: 'json',
            method: 'GET',
            success: function (data) {
                if (data.code == 0) {
                    var profile = data.data;
                    currentSeller = profile;
                    console.log('更新seller');
                    console.log(currentSeller);
                    beginCatch();
                }
            },
            error: function (data) {
                clearInterval(autorefresh);
            }
        });
    }
}


function getCatchUrl(site) {
    if(site === 'co.jp'){
        var url = "https://sellercentral-japan.amazon.com";
    }else{
        var url = "https://sellercentral.amazon." + site + "";
    }
    return url + baseUri;
}

//获取请求session的参数
function getRequestParam(date, page)
{
    if (page === undefined) {
        page = 0;
    }
    return {
        sortColumn:17,
        filterFromDate: date,
        filterToDate: date,
        fromDate:date,
        toDate:date,
        cols:'/c0/c1/c2/c3/c4/c5/c6/c7/c8/c9/c10/c11/c12/c13/c14/c15/c16',
        reportID: '102:DetailSalesTrafficBySKU',
        sortIsAscending: '0',
        currentPage: page,
        dateUnit: '1',
        viewDateUnits: 'ALL',
        runDate:'',
        _: (new Date()).getTime(),
    }
}

//将成功的记录删除到特定的marketplace中
function logSuccess(date, marketId) {
    var marketplaces = currentSeller.marketplace;
    
    for(var i = 0; i < marketplaces.length; i++) {
        if (marketplaces[i].marketplaceId === marketId) {
            currentSeller.marketplace[i].traffics.push(date);
            currentSeller.marketplace[i].unTraffics.remove(date);
        }
    }
}

function formatDate(milliseconds) {

    var dateObj = new Date();
    dateObj.setTime(milliseconds);
    var month = (dateObj.getMonth() + 1);
    var start =
        (month < 10 ? "0" + month : month)
        + '/' +
        (dateObj.getDate() < 10 ? "0"+dateObj.getDate() : dateObj.getDate())
        + '/'  +
        dateObj.getFullYear();
    return start;
}

function  putLogCache(date, site, flag) {
    if (flag) {
        //记录成功数据


    }
    if (!(date in articleData.success)) {
        articleData.success.push(date);
        chrome.storage.local.set({collect_log: collection_logs}, function () {
            console.log('保存成功' + date);
            popupInsertLiLog(date, 'success');
        });
    }
}

function getLogCache() {
    var log = chrome.storage.local.get(['collect_log'], function (items) {
        return items.collect_log;
    });

    return  log === undefined ? [] : log;
}

function getLogLisCache() {
    var log = chrome.storage.local.get(['collect_log_lis'], function (items) {
        return items.collect_log_lis;
    });

    return  log === undefined ? [] : log;

}

function getProfileCache() {
    var log = chrome.storage.local.get(['customerProfile'], function (items) {
        return items.customerProfile;
    });

    return  log === undefined ? {
        sellerId: '',
        marketplaceId: ''
    } : log;
}


function popupInsertLiLog(date, state) {
    log_lis.push(getLogLi(date, state));
    chrome.storage.local.set({collect_log_lis: log_lis});
}

function getLogLi(site, date, status)
{
    if (status == 'success') {
        return '<li>站点['+site+']:'+date+'  <span style="color: green">记录成功!</span></li>';
    }  else {
        return '<li>站点['+site+']:'+date+' <span style="color: red">失败!</span></li>';
    }
}

